package com.itheima.controller;

import com.itheima.pojo.Emp;
import com.itheima.pojo.LoginInfo;
import com.itheima.pojo.Result;
import com.itheima.service.EmpService;
import com.itheima.utils.CurrentHolder;
import com.itheima.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

//登录控制层
@RestController
public class LoginController {
    @Autowired
    private EmpService empService;

    @PostMapping("/login")
    public Result login(@RequestBody Emp emp) {
        // 调用业务逻辑层登录
        LoginInfo loginInfo = empService.login(emp);
        if (loginInfo != null) {
            // 使用统一的CurrentHolder存储用户ID
            CurrentHolder.setCurrentId(loginInfo.getId());

            // 生成JWT令牌
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", loginInfo.getId());
            claims.put("username", loginInfo.getUsername());
            claims.put("name", loginInfo.getName());

            String token = JwtUtils.generateJwt(claims);

            loginInfo.setToken(token);
            return Result.success(loginInfo);
        }
        return Result.error("用户名或密码错误");
    }
}